package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redisService.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判断头上是否贴了拦截注解
        HandlerMethod hm = (HandlerMethod) handler;

        if (hm.hasMethodAnnotation(RequireLongin.class)) {
            String token = request.getHeader("token");
            UserInfo userInfo = userInfoRedisService.getHeader(token);
            System.err.println(userInfo);
            if (userInfo == null) {
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write("请先进行登录");
                return  false;
            }
        }
        //没有就放行
        return true;
    }
}
